package com.ruoyi.loan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.ruoyi.loan.entity.Image;
import com.ruoyi.loan.mapper.ImageMapper;
import com.ruoyi.loan.service.ImageService;
import com.ruoyi.loan.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lin
 * @Date 2022/4/5 0:20
 */
@Service
public class ImageServiceImpl extends ServiceImpl<ImageMapper, Image> implements ImageService {

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private FileUtils fileUtils;

    @Override
    public List<Integer> uploadPoorImages(MultipartFile[] multipartFiles) {

        // 判断是否有文件
        if (multipartFiles == null || multipartFiles.length == 0){
            throw new RuntimeException("上传的文件为空！");
        }
        // 进行文件上传
        List<Integer> imgIds = new ArrayList<>(multipartFiles.length);
        for (MultipartFile multipartFile : multipartFiles){
            Image image = new Image();
            // 上传文件
            String path = FileUtils.upLoadFile(multipartFile,FileUtils.LOAN_IMG);
            image.setPath(path);
            int imgId = imageMapper.insert(image);
            if (imgId < 1){
                throw new RuntimeException("图片上传失败，请重试");
            }
            imgIds.add(image.getId());
        }
        return imgIds;
    }

    @Override
    public List<Image> selectImagesByLoanId(Integer loanId) {
        List<Image> imageList = imageMapper.selectList(new QueryWrapper<Image>().eq("key_id", loanId));
        for (Image image : imageList) {
            String path = image.getPath();
            String showFilePath = fileUtils.getShowFilePath(path);
            image.setPath(showFilePath);
        }
        return imageList;
    }
}
